package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.RechargeDTO;
import com.example.dto.RechargeRecordQueryDTO;
import com.example.service.RechargeService;
import com.example.service.UserService;
import com.example.util.JwtUserUtil;
import com.example.vo.RechargeRecordVO;
import com.example.vo.UserBalanceVO;
import com.example.vo.UserInfoVO;
import com.example.service.UserBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 充值控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class RechargeController {
    
    @Autowired
    private RechargeService rechargeService;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUserUtil jwtUserUtil;
    
    /**
     * 用户充值
     */
    @PostMapping("/recharge")
    @RequirePermission("user:recharge")
    public Result<String> userRecharge(@RequestBody RechargeDTO rechargeDTO) {
        return rechargeService.userRecharge(rechargeDTO);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    @RequirePermission("user:info:view")
    public Result<UserInfoVO> getUserInfo() {
        UserInfoVO userInfo = userService.getCurrentUserInfo();
        return Result.success(userInfo);
    }
    
    /**
     * 获取当前用户余额信息
     */
    @GetMapping("/balance/my")
    @RequirePermission("user:balance:view")
    public Result<UserBalanceVO> getMyBalance() {
        return userBalanceService.getMyBalance();
    }
    
    /**
     * 获取当前用户充值记录
     */
    @GetMapping("/recharge/records")
    @RequirePermission("user:recharge:records")
    public Result<PageResult<RechargeRecordVO>> getMyRechargeRecords(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) Double minAmount,
            @RequestParam(required = false) Double maxAmount,
            @RequestParam(required = false) String rechargeType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String orderNo) {

        System.out.println("=== 充值记录API调用 ===");
        System.out.println("参数: page=" + page + ", size=" + size + ", status=" + status);
        System.out.println("金额范围: minAmount=" + minAmount + ", maxAmount=" + maxAmount);
        System.out.println("充值类型: " + rechargeType);
        System.out.println("时间范围: startTime=" + startTime + ", endTime=" + endTime);
        System.out.println("当前用户ID: " + jwtUserUtil.getCurrentUserIdFromContext());
        
        RechargeRecordQueryDTO queryDTO = new RechargeRecordQueryDTO();
        
        // 设置金额范围
        if (minAmount != null) {
            queryDTO.setMinAmount(java.math.BigDecimal.valueOf(minAmount));
        }
        if (maxAmount != null) {
            queryDTO.setMaxAmount(java.math.BigDecimal.valueOf(maxAmount));
        }
        
        queryDTO.setRechargeType(rechargeType);
        queryDTO.setStatus(status);
        
        // 处理时间参数，支持多种格式
        if (startTime != null && !startTime.trim().isEmpty()) {
            try {
                // 先尝试标准格式
                if (startTime.contains("T")) {
                    queryDTO.setStartTime(LocalDateTime.parse(startTime));
                } else if (startTime.length() == 19) {
                    // yyyy-MM-dd HH:mm:ss 格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    queryDTO.setStartTime(LocalDateTime.parse(startTime, formatter));
                } else if (startTime.length() == 10) {
                    // yyyy-MM-dd 格式，补充时间为 00:00:00
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    queryDTO.setStartTime(LocalDateTime.parse(startTime + " 00:00:00", 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            } catch (Exception e) {
                System.out.println("解析开始时间失败: " + startTime + ", 错误: " + e.getMessage());
            }
        }
        
        if (endTime != null && !endTime.trim().isEmpty()) {
            try {
                // 先尝试标准格式
                if (endTime.contains("T")) {
                    queryDTO.setEndTime(LocalDateTime.parse(endTime));
                } else if (endTime.length() == 19) {
                    // yyyy-MM-dd HH:mm:ss 格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    queryDTO.setEndTime(LocalDateTime.parse(endTime, formatter));
                } else if (endTime.length() == 10) {
                    // yyyy-MM-dd 格式，补充时间为 23:59:59
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    queryDTO.setEndTime(LocalDateTime.parse(endTime + " 23:59:59", 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            } catch (Exception e) {
                System.out.println("解析结束时间失败: " + endTime + ", 错误: " + e.getMessage());
            }
        }
        
        queryDTO.setOrderNo(orderNo);
        
        System.out.println("最终查询条件: " + queryDTO);
        
        return rechargeService.getMyRechargeRecords(page, size, queryDTO);
    }
    
    /**
     * 根据订单号查询充值记录
     */
    @GetMapping("/record/{orderNo}")
    public Result<RechargeRecordVO> getRechargeRecordByOrderNo(@PathVariable String orderNo) {
        return rechargeService.getRechargeRecordByOrderNo(orderNo);
    }
    
    /**
     * 获取充值统计信息（管理员使用）
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getRechargeStatistics() {
        return rechargeService.getRechargeStatistics();
    }
    
    /**
     * 获取当前用户充值统计信息
     */
    @GetMapping("/my-statistics")
    public Result<Map<String, Object>> getMyRechargeStatistics() {
        return rechargeService.getMyRechargeStatistics();
    }
    
    /**
     * 获取今日充值统计
     */
    @GetMapping("/today-statistics")
    public Result<Map<String, Object>> getTodayRechargeStatistics() {
        return rechargeService.getTodayRechargeStatistics();
    }
    
    /**
     * 根据时间范围获取充值统计
     */
    @GetMapping("/statistics/date-range")
    public Result<Map<String, Object>> getRechargeStatisticsByDateRange(
            @RequestParam String startTime,
            @RequestParam String endTime) {
        return rechargeService.getRechargeStatisticsByDateRange(startTime, endTime);
    }
    
    /**
     * 更新充值记录状态（管理员使用）
     */
    @PutMapping("/update-status")
    public Result<Void> updateRechargeStatus(@RequestParam String orderNo,
                                            @RequestParam Integer status,
                                            @RequestParam(required = false) String remark) {
        return rechargeService.updateRechargeStatus(orderNo, status, remark);
    }
    

}
